package gui.Main;

import gui.mapper.NodeListing;

import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

import proxyCommand.GlobalObjectId;
import proxyCommand.HyPeerWebProxy;
import proxyCommand.LocalObjectId;
import proxyCommand.PeerCommunicator;

/**
 * The central GUI used to display information about the HyPeerWeb and debug information
 * 
 * @author Matthew Smith
 *
 */
public class GUI extends JFrame
{
	private static GUI singleton = null;
	
	/** Main Debugger Panel**/
	private HyPeerWebDebugger debugger;
	
	private HyPeerWebProxy hypeerweb;
	private JScrollPane scrollPane;
	
	private GlobalObjectId globalObjectId;
	
	/**
	 * Creates and initializes the GUI as being the root
	 */
	public GUI(HyPeerWebProxy hypeerweb, GlobalObjectId globalObjectId){
		this.hypeerweb = hypeerweb;
		this.globalObjectId = globalObjectId;
		this.setTitle("HyPeerWeb DEBUGGER V 1.1");

		this.addWindowListener(new WindowAdapter() {
			  public void windowClosing(WindowEvent we) {
				shutdown();
				PeerCommunicator.stopThisConnection();
				
			    System.exit(0);
			  }
			});
		
		debugger = new HyPeerWebDebugger(this);
		scrollPane = new JScrollPane(debugger);
		scrollPane.setPreferredSize(new Dimension(debugger.WIDTH+20, debugger.HEIGHT));
		
		this.getContentPane().add(scrollPane);
		
		this.pack();
	}
	
	private void shutdown(){
		hypeerweb.disconnectFromGUI(globalObjectId);

	}
	
	public static GUI getSingleton(HyPeerWebProxy hypeerweb, GlobalObjectId globalObjectId){
		if(singleton == null){
			try{
				singleton = new GUI(hypeerweb, globalObjectId);
						
				singleton.setVisible(true);
			}
			catch(Exception e)	{
				JOptionPane.showMessageDialog(null, e.getMessage(), "ERROR",JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
				System.exit(1);
			}
		}
		return singleton;
	}

	/**
	 * Retrieves the HyPeerWeb Debugging Panel
	 * @return HyPeerWebDebugger
	 */
	public HyPeerWebDebugger getHyPeerWebDebugger() {
		return debugger;
	}
	
	public HyPeerWebProxy getHyPeerWeb(){
		return hypeerweb;
	}
	
	public void printToTracePanel(Object msg){
		debugger.getTracePanel().print(msg);
	}
	
	public LocalObjectId getLocalObjectId(){
		return globalObjectId.getLocalObjectId();
	}
	
	public GlobalObjectId getGlobalObjectId(){
		return globalObjectId;
	}
	
	public void updateNodeList() {
		debugger.getMapper().getNodeListing().rebootListSize();
	}
	
	public void closeGui() {
		PeerCommunicator.stopThisConnection();
		System.exit(0);
	}
	
	/**
	 * Start Point of the Program
	 */
//	public static void main (String[] args){
//		HyPeerWeb.getSingleton();
//	}
}
